<template>
  <a-modal
    :visible="visible"
    unmount-on-close
    @ok="handleOk"
    @cancel="handleCancel"
    :width="600"
  >
    <template #title> {{ data?.id ? '编辑' : '新增' }}日程待办 </template>
    <a-form :model="formData.data" size="small" :rules="rules" ref="refForm">
      <a-form-item field="text" label="待办内容" show-colon>
        <a-textarea
          v-model="formData.data.text"
          :auto-size="{
            minRows: 4
          }"
          allow-clear
        />
      </a-form-item>
      <a-form-item label="截止时间" show-colon field="endTime">
        <a-range-picker
          value-format="YYYY-MM-DD HH:mm"
          format="YYYY-MM-DD HH:mm"
          show-time
          v-model="formData.data.endTime"
          :disabledDate="
            (current) => dayjs(current).isBefore(dayjs(date), 'day')
          "
        />
        <!-- <template #help> <a-switch size="small"></a-switch>全天 </template> -->
      </a-form-item>
      <a-form-item label="提醒时间" show-colon field="remindTime">
        <a-select v-model="formData.data.remindTime">
          <a-option
            v-for="item in REMIND_TIME"
            :key="item.value"
            :value="item.value"
          >
            {{ item.label }}
          </a-option>
        </a-select>
        <template #extra>
          <a-switch
            size="small"
            v-model="formData.data.isRepeat"
            :checked-value="1"
            :unchecked-value="2"
          ></a-switch
          >重复提醒规则
        </template>
      </a-form-item>
      <a-form-item
        label="提醒时间"
        show-colon
        field=""
        v-show="formData.data.isRepeat === 1"
      >
        <a-space>
          <span>每</span>
          <a-input-number
            v-model="formData.data.reminderFrequencyNum"
            style="width: 100px"
            hide-button
            :min="1"
            :precision="0"
            :max="formData.data.reminderFrequencyUnit !== '时' ? 60 : undefined"
          ></a-input-number>
          <a-select
            style="width: 100px"
            v-model="formData.data.reminderFrequencyUnit"
          >
            <a-option value="时">时</a-option>
            <a-option value="分">分</a-option>
            <a-option value="秒">秒</a-option>
          </a-select>
          <span>重复提醒一次</span>
        </a-space>
      </a-form-item>
      <a-form-item label="新增参与者" show-colon field="participant">
        <a-select
          v-model="formData.data.participant"
          multiple
          :popup-visible="false"
          @popup-visible-change="(val, type) => onParticipatorChange(val, 1)"
          :max-tag-count="3"
          @remove="(item, type) => remove(item, 1)"
          value-key="uid"
        >
          <a-option v-for="item in participant" :key="item.uid" :value="item">
            {{ item.name }}
          </a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="可见范围" show-colon>
        <a-select
          v-model="formData.data.range"
          multiple
          :popup-visible="false"
          @popup-visible-change="(val, type) => onParticipatorChange(val, 2)"
          :max-tag-count="3"
          @remove="(item, type) => remove(item, 2)"
          value-key="uid"
        >
          <a-option v-for="item in range" :key="item.uid" :value="item">
            {{ item.name }}
          </a-option>
        </a-select>
        <template #help>
          <div>被新增的参与者的日程待办会自动新增一条相同的日程</div></template
        >
      </a-form-item>
      <a-form-item label="提示颜色" show-colon field="color">
        <!-- <a-space wrap>
          <div
            v-for="item in colorEnums"
            :key="item"
            class="color-item"
            :style="{
              backgroundColor: item
            }"
          ></div>
        </a-space> -->
        <div class="color">
          <div
            v-for="item in colorEnums"
            :key="item"
            class="color-item"
            :style="{
              backgroundColor: item
            }"
            :title="item"
            @click="isCheckColor(item)"
          >
            <icon-check
              v-show="isCheck && formData.data.color == item"
              class="check"
            />
          </div>
          <a-space :size="0"
            ><ColorPicker
              v-model:color="customColor"
              @change="changeCustomColor"
            ></ColorPicker>
            <span class="w-20">自定义</span>
          </a-space>
        </div>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button
        @click="handleOk"
        type="primary"
        v-if="data.id ? isOverStartTime() : true"
        >确认</a-button
      >
    </template>

    <HumanOrDepartmentModal
      v-model:visible="humanOrDepartmentModalVisible"
      @humanOrDepartmentEmit="humanOrDepartmentEmit"
      :data="currHumanOrDepartmentModalData"
    />
  </a-modal>
</template>

<script lang="ts" setup>
import ColorPicker from '@/components/ColorPiker.vue';
import HumanOrDepartmentModal from '@/components/HumanOrDepartmentModal/index.vue';
import dayjs from 'dayjs';
import { cloneDeep } from 'lodash';
import { REMIND_TIME } from '@/utils/constants';
const props = withDefaults(
  // 参数说明
  defineProps<{
    visible: boolean;
    date: Date; // 当前日期
    data?: any;
  }>(),
  {}
);

let customColor = ref('#000'); // 自定义颜色
const emit = defineEmits(['update:visible', 'scheduleEmit']);

watch(
  () => props.visible,
  (val: boolean) => {
    if (val) {
      if (props.data?.id) {
        formData.data = handlePropsData(cloneDeep(props.data));
      } else {
        reset();
      }
    }
  }
);

const handlePropsData = (data: any) => {
  const participantIdArr = data.participantId.split(',');
  const participantNameArr = data.participantName.split(',');
  const participantDeptArr = data.participantDepart.split(',');
  const participantDeptNameArr = data.participantDepartName.split(',');

  const rangeIdArr = data.rangeId.split(',');
  const rangeNameArr = data.rangeName.split(',');
  const rangeDeptArr = data.rangeDepart.split(',');
  const rangeDeptNameArr = data.rangeDepartName.split(',');

  const participantLen = participantIdArr.length;
  const participantDeptLen = participantDeptArr.length;
  const rangeLen = rangeIdArr.length;
  const rangeDeptLen = rangeDeptArr.length;

  for (let i = 0; i < participantLen; i++) {
    participant.value.push({
      id: +participantIdArr[i],
      name: participantNameArr[i],
      type: 2, // 人员默认2,
      uid: `${participantIdArr[i]}-2`
    });
  }
  for (let i = 0; i < participantDeptLen; i++) {
    participant.value.push({
      id: +participantDeptArr[i],
      name: participantDeptNameArr[i],
      type: 1, // 部门默认1,
      uid: `${participantDeptArr[i]}-1`
    });
  }
  for (let i = 0; i < rangeLen; i++) {
    range.value.push({
      id: +rangeIdArr[i],
      name: rangeNameArr[i],
      type: 2, // 人员默认2,
      uid: `${rangeIdArr[i]}-2`
    });
  }
  for (let i = 0; i < rangeDeptLen; i++) {
    range.value.push({
      id: +rangeDeptArr[i],
      name: rangeDeptNameArr[i],
      type: 1, // 部门默认1,
      uid: `${rangeDeptArr[i]}-1`
    });
  }
  data.participant = participant.value;
  data.range = range.value;

  data.endTime = data.endTime.split(',');
  customColor.value = data.color;
  isCheck.value = true;
  return data;
};

let refForm = ref();

const rules = {
  text: [{ required: true, message: '请输入待办内容' }],
  endTime: [{ required: true, message: '请选择截止时间' }],
  remindTime: [{ required: true, message: '请选择提醒时间' }],
  // participant: [{ required: true, message: '请选择参与者' }],
  color: [{ required: true, message: '请选择提示颜色' }]
};

let humanOrDepartmentModalVisible = ref(false);

let participant = ref([]);
let participantIds = ref([]);
let range = ref([]);
let rangeIds = ref([]);
const formData = reactive({
  data: {
    date: dayjs(props.date).format('YYYY-MM-DD'), // 待办日期
    text: '', // 待办内容
    endTime: '', // 截止时间
    remindTime: undefined, // 提醒时间
    isRepeat: 2, // 是否重复
    reminderFrequencyNum: undefined, // 提醒频次的数字
    reminderFrequencyUnit: '时', // 提醒频次的单位
    participantId: [], // 参与者人员ids
    participantName: [], // 参与者名称
    participantDepartName: [], // 参与者部门名称
    participantDepart: [], // 参与部门i
    participant: [], // 参与者显示的数据
    rangeId: [], // 可见范围人员id
    rangeName: [], // 可见范围名称
    rangeDepart: [], // 可以范围部门id
    rangeDepartName: [], // 可见范围部门名称
    range: [], // 可见范围显示的数据
    color: '', //颜色,
    initiatorId: +localStorage.getItem('userId'), // 发起人id,
    done: 2 //未完成默认传2
  }
});

let orginData = cloneDeep(formData.data);

let currType = 1; // 判断是选择参与者还是可见范围 1参与者 2可见范围
let currHumanOrDepartmentModalData = ref({});
const onParticipatorChange = (visible: boolean, type: 1 | 2) => {
  if (type === 1) {
    currHumanOrDepartmentModalData.value = participant.value;
  } else {
    currHumanOrDepartmentModalData.value = range.value;
  }
  console.log(
    '=================currHumanOrDepartmentModalDatacurrHumanOrDepartmentModalData==================='
  );
  console.log(currHumanOrDepartmentModalData.value);
  console.log('====================================');
  humanOrDepartmentModalVisible.value = visible;
  currType = type;
};

const humanOrDepartmentEmit = (data: any) => {
  if (currType === 1) {
    participant.value = data;
    formData.data.participant = data;
    console.log(
      '=================currHumanOrDepartmentModalDatacurrHumanOrDepartmentModalData==================='
    );
    console.log(data);
    console.log('====================================');
  } else {
    range.value = data;
    rangeIds.value = data.map((item: any) => item.id);
    formData.data.range = data;
  }
};

// 删除参与者/可见范围
const remove = (record: any, type: 1 | 2) => {
  if (type === 1) {
    participant.value = participant.value.filter(
      (item) => item.uid !== record.uid
    );
    formData.data.participant = participant.value;
    participantIds.value = participant.value.map((item) => item.id);
  } else {
    range.value = range.value.filter((item) => item.uid !== record.uid);
    formData.data.range = range.value;
    rangeIds.value = range.value.map((item) => item.id);
  }
  console.log('====================================');
  console.log(participant.value, participantIds.value);
  console.log('====================================');
};

const colorEnums = [
  '#f5bf41',
  '#f09840',
  '#ef875f',
  '#ff0000',
  '#72c140',
  '#62ca82',
  '#5fced9',
  '#5abfc0',
  '#5a9cf8',
  '#165dff',
  '#57b1e9',
  '#785ee9',
  '#494fe0'
];

let isCheck = ref(false); // 是否选中系统已有的颜色

// 选中系统已有的颜色
const isCheckColor = (color: string) => {
  formData.data.color = color;
  isCheck.value = true;
};

// 自定义颜色
const changeCustomColor = (color: string) => {
  formData.data.color = customColor.value;
  isCheck.value = false;
};

// 判断当前时间是否超过了开始时间
const isOverStartTime = () => {
  return dayjs().isBefore(dayjs(formData.data.endTime[0]));
};

const handleOk = async () => {
  try {
    // if (await refForm.value.validate()) return;

    formData.data.participantId = participant.value
      .filter((item: any) => item.uid[item.uid.length - 1] === '2')
      .map((el: any) => el.id);
    formData.data.participantName = participant.value
      .filter((item: any) => item.uid[item.uid.length - 1] === '2')
      .map((el: any) => el.name);
    formData.data.participantDepart = participant.value
      .filter((item: any) => item.uid[item.uid.length - 1] === '1')
      .map((el: any) => el.id);
    formData.data.participantDepartName = participant.value
      .filter((item: any) => item.uid[item.uid.length - 1] === '1')
      .map((el: any) => el.name);

    formData.data.rangeId = range.value
      .filter((item: any) => item.uid[item.uid.length - 1] === '2')
      .map((el: any) => el.id);
    formData.data.rangeName = range.value
      .filter((item: any) => item.uid[item.uid.length - 1] === '2')
      .map((el: any) => el.name);
    formData.data.rangeDepart = range.value
      .filter((item: any) => item.uid[item.uid.length - 1] === '1')
      .map((el: any) => el.id);
    formData.data.rangeDepartName = range.value
      .filter((item: any) => item.uid[item.uid.length - 1] === '1')
      .map((el: any) => el.name);

    const temp = cloneDeep(formData.data);
    temp.endTime = temp.endTime.join(',');
    temp.participantId = temp.participantId.join(',');
    temp.participantDepart = temp.participantDepart.join(',');
    temp.participantName = temp.participantName.join(',');
    temp.participantDepartName = temp.participantDepartName.join(',');
    temp.rangeId = temp.rangeId.join(',');
    temp.rangeDepart = temp.rangeDepart.join(',');
    temp.rangeName = temp.rangeName.join(',');
    temp.rangeDepartName = temp.rangeDepartName.join(',');
    console.log('====================================');
    console.log(temp);
    console.log('====================================');
    emit('update:visible', false);
    emit('scheduleEmit', temp);
  } catch (error: unknown) {
    console.log(error);
  }
};

const handleCancel = () => {
  emit('update:visible', false);
};

// 重置数据
const reset = () => {
  formData.data = cloneDeep(orginData);
  range.value = [];
  participant.value = [];
  rangeIds.value = [];
  participantIds.value = [];
  isCheck.value = false;
  customColor.value = '#000';
};
</script>

<style lang="less" scoped>
// 每行8个，用grid布局
.color {
  display: grid;
  grid-template-columns: repeat(7, 25px);
  grid-template-rows: repeat(2, 25px);
  gap: 10px;
  .color-item {
    width: 25px;
    height: 25px;
    border-radius: 50%;
    cursor: pointer;
    background-color: #ff0000;
    text-align: center;
    line-height: 25px;
  }

  .check {
    color: #fff;
  }
}
</style>
